package com.ocom.aiot.controller;


import com.github.pagehelper.PageInfo;
import com.ocom.aiot.service.MjDeviceInfoService;
import com.ocom.aiot.vo.accessdevice.AddDeviceInfoVo;
import com.ocom.aiot.vo.accessdevice.GetDeviceInfoVo;
import com.ocom.aiot.vo.accessdevice.SetDeviceStatusVo;
import com.ocom.aiot.vo.accessdevice.SetMjDeviceStatusBySaasVo;
import com.ocom.common.constant.AiotUrl;
import com.ocom.common.entity.aiot.EntityMjDeviceInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@RestController
public class AccessDeviceController {

    @Autowired
    private MjDeviceInfoService mjDeviceInfoService;

    @Resource
    private RedisUtil redisUtil;

    //2.6.1.获取设备信息（getDeviceInfo）
    @PostMapping(AiotUrl.Url_Aiot_AccessDeviceGetDeviceInfo)
    public Result AccessDeviceGetDeviceInfo(@Validated @RequestBody GetDeviceInfoVo getDeviceInfoVo){
        Map<String, Object> map = new HashMap<>();
        try {
            List<EntityMjDeviceInfo> entityMjDeviceInfos = mjDeviceInfoService.AccessDeviceGetDeviceInfo(getDeviceInfoVo);
            entityMjDeviceInfos.forEach(item -> {
                item.setCommTime(getCommTime(item.getDeviceNo(),item.getCommTime()));
            });
            PageInfo<EntityMjDeviceInfo> entityXfDeviceInfoPageInfo = new PageInfo<>(entityMjDeviceInfos);
            map.put("total",entityXfDeviceInfoPageInfo.getTotal());
            map.put("list",entityMjDeviceInfos);

        }catch (Exception exception){
            log.error("获取设备信息失败："+exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"获取设备信息失败");
        }

        return ResultUtil.success(map);
    }

    // 2.6.2.添加设备信息（addDeviceInfo）
    @PostMapping(AiotUrl.Url_Aiot_AccessDeviceAddDeviceInfo)
    public Result AccessDeviceAddDeviceInfo(@Validated @RequestBody AddDeviceInfoVo addDeviceInfoVo){
        if (addDeviceInfoVo.getDeviceNo() == null){
            log.error("设备编号（出厂号）为空");
            return ResultUtil.error(ResultEnum.Err_203,"设备编号（出厂号）为空");
        }
        if (addDeviceInfoVo.getCommMode() == null){
            log.error("通讯协议为空");
            return ResultUtil.error(ResultEnum.Err_203,"通讯协议为空");
        }
        if (addDeviceInfoVo.getDeviceType() ==null){
            log.error("设备类型为空");
            return ResultUtil.error(ResultEnum.Err_203,"设备类型为空");
        }
        if (addDeviceInfoVo.getDeviceVerType() == null){
            log.error("设备机型为空");
            return ResultUtil.error(ResultEnum.Err_203,"设备机型为空");
        }
        try {
            EntityMjDeviceInfo entityMjDeviceInfo = mjDeviceInfoService.GetDeviceByDeviceNo(addDeviceInfoVo.getDeviceNo());
            List<String> list = new ArrayList<>();
            if (entityMjDeviceInfo != null){
                if (addDeviceInfoVo.getDeviceNo().equals(entityMjDeviceInfo.getDeviceNo())){
                    list.add(addDeviceInfoVo.getDeviceNo());
                    log.error("设备已存在，添加失败: "+list);
                    return ResultUtil.error(ResultEnum.Err_3003);
                }

            } else {
                try {
                    mjDeviceInfoService.AccessDeviceAddDeviceInfo(addDeviceInfoVo);
                }catch (Exception exception){
                    log.error(exception.getMessage());
                    return ResultUtil.error(ResultEnum.Err_2009,exception.getMessage());
                }
            }
        }catch (Exception exception){
            log.error(exception.getMessage());
        }

        return ResultUtil.success();
    }


    // 2.6.3.修改设备信息（updateDeviceInfo）
    @PostMapping(AiotUrl.URL_Aiot_AccessDeviceUpdateDeviceInfo)
    public Result AccessDeviceUpdateDeviceInfo(@Validated @RequestBody EntityMjDeviceInfo entityMjDeviceInfo){
        if (entityMjDeviceInfo.getDeviceNo() == null ){
            log.error("设备编号（出厂号）为空");
            return ResultUtil.error(ResultEnum.Err_203,"设备编号（出厂号）为空");
        }

        try {
            mjDeviceInfoService.AccessDeviceUpdateDeviceInfo(entityMjDeviceInfo);
        }catch (Exception exception){
            log.error("修改设备信息失败："+exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"修改设备信息失败");
        }
        return ResultUtil.success();
    }

    //2.6.4.删除设备信息（deleteDeviceInfo）
    @PostMapping(AiotUrl.URL_Aiot_AccessDeviceDeleteDeviceInfo)
    public Result AccessDeviceDeleteDeviceInfo(@RequestParam("deviceNo") String deviceNo ,
                                                @RequestParam(required = false,defaultValue = "0") Integer force){
        if (deviceNo == null ){
            log.error("设备编号参数为空");
            return ResultUtil.error(ResultEnum.Err_203,"设备编号参数为空");
        }

        try {
            EntityMjDeviceInfo entityMjDeviceInfo = mjDeviceInfoService.AccessDeviceDeleteDeviceInfo(deviceNo,force);
            if (entityMjDeviceInfo!=null){
                log.error("删除失败，设备激活状态");
                return ResultUtil.error(ResultEnum.Err_3018, "删除失败，设备激活状态");
            }
        }catch (Exception exception){
            log.error("删除设备信息失败："+exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"删除设备信息失败");
        }
        return ResultUtil.success();
    }

    // 门禁SaaS平台设置设备状态（/AccessDevice/SetDeviceStatus）
    @PostMapping(AiotUrl.Url_Aiot_AccessDeviceSetDeviceStatus)
    public Result AccessDeviceSetDeviceStatus(@Validated @RequestBody SetDeviceStatusVo setDeviceStatusVo){
        if (setDeviceStatusVo.getSaasNo().isEmpty()){
            log.error("saas平台绑定编号为空: "+setDeviceStatusVo);
            return ResultUtil.error(ResultEnum.Err_203,"saas平台绑定编号");
        }
        if (setDeviceStatusVo.getDeviceNo().isEmpty()){
            log.error("设备编号（出厂号）为空");
            return ResultUtil.error(ResultEnum.Err_203,"设备编号（出厂号）为空");
        }
        if (setDeviceStatusVo.getComId() == null){
            log.error("saas平台绑定单位id为空");
            return ResultUtil.error(ResultEnum.Err_203,"saas平台绑定单位id为空");
        }
        if (setDeviceStatusVo.getStatus() == null){
            log.error("启用状态为空");
            return ResultUtil.error(ResultEnum.Err_203,"启用状态为空");
        }
        if (setDeviceStatusVo.getAgentId() == null){
            log.error("saas平台绑定代理商id为空");
            return ResultUtil.error(ResultEnum.Err_203,"saas平台绑定代理商id为空");
        }


        try {
            mjDeviceInfoService.AccessDeviceSetDeviceStatus(setDeviceStatusVo);
        }catch (Exception exception){
            log.error("SaaS平台设置设备状态更新操作失败");
            return ResultUtil.error(ResultEnum.Err_2009,"SaaS平台设置设备状态更新操作失败");
        }

        return ResultUtil.success();
    }

    // 3.3.SaaS平台激活(禁用)门禁设备(SetMjDeviceStatusBySaas)
    @PostMapping(AiotUrl.Url_Aiot_SetMjDeviceStatusBySaas)
    public Result SetMjDeviceStatusBySaas(@Validated @RequestBody SetMjDeviceStatusBySaasVo setMjDeviceStatusBySaasVo){
        log.info("aiot 激活参数 【{}】",setMjDeviceStatusBySaasVo);
        if (setMjDeviceStatusBySaasVo.getSaasNo().isEmpty()){
            log.error("Saas平台绑定编号参数为空");
            return ResultUtil.error(ResultEnum.Err_203,"Saas平台绑定编号参数为空");
        }
        if (setMjDeviceStatusBySaasVo.getComId()==null){
            log.error("单位编号参数为空");
            return ResultUtil.error(ResultEnum.Err_203,"单位编号参数为空");
        }
        if (setMjDeviceStatusBySaasVo.getDeviceNo().isEmpty()){
            log.error("设备编号参数为空");
            return ResultUtil.error(ResultEnum.Err_203,"设备编号参数为空");
        }

        EntityMjDeviceInfo entityMjDeviceInfo = null;
        try {
            entityMjDeviceInfo = mjDeviceInfoService.GetDeviceByDeviceNo(setMjDeviceStatusBySaasVo.getDeviceNo());
            if (entityMjDeviceInfo == null) {
                //注销 不存在 返回成功
                if(setMjDeviceStatusBySaasVo.getStatus() == 0){
                    return ResultUtil.success();
                }
                log.error("设备不存在");
                return ResultUtil.error(ResultEnum.Err_2013);
            }
            //删除
            if (setMjDeviceStatusBySaasVo.getStatus() == 0){

                //在其他单位用
                if(entityMjDeviceInfo.getComId()!=setMjDeviceStatusBySaasVo.getComId() || entityMjDeviceInfo.getComId()==0l){
                    return ResultUtil.success();
                }


                if (entityMjDeviceInfo.getStatus() == 0) {
                    log.error("设备已注销");
                    return ResultUtil.error(ResultEnum.Err_3022);
                }
                if (StringUtils.isNotNull(entityMjDeviceInfo.getPSaasNo()) && !setMjDeviceStatusBySaasVo.getSaasNo().equals(entityMjDeviceInfo.getPSaasNo())) {
                    log.error("设备已指定其他SaaS平台");
                    return ResultUtil.error(ResultEnum.Err_3019);
                }
//                if (StringUtils.isNull(entityMjDeviceInfo.getPComId())) {
//                    if (StringUtils.isNotNull(entityMjDeviceInfo.getPAgentId()) && !setMjDeviceStatusBySaasVo.getAgentId().equals(entityMjDeviceInfo.getPAgentId())) {
//                        log.error("设备已指定其他代理商");
//                        return ResultUtil.error(ResultEnum.Err_3020);
//                    }
//                }
                if (setMjDeviceStatusBySaasVo.getComId() != entityMjDeviceInfo.getComId()) {
                    log.error("设备已指定其他单位");
                    return ResultUtil.error(ResultEnum.Err_3021);
                }

            }
            if (setMjDeviceStatusBySaasVo.getStatus() == 1) {
                if (entityMjDeviceInfo.getStatus() == 1) {
                    log.error("设备已激活");
                    return ResultUtil.error(ResultEnum.Err_3018);
                }
                if (StringUtils.isNotNull(entityMjDeviceInfo.getPSaasNo()) && !setMjDeviceStatusBySaasVo.getSaasNo().equals(entityMjDeviceInfo.getPSaasNo())) {
                    log.error("设备已指定其他SaaS平台");
                    return ResultUtil.error(ResultEnum.Err_3019);
                }
                if (StringUtils.isNull(entityMjDeviceInfo.getPComId())) {
                    if (StringUtils.isNotNull(entityMjDeviceInfo.getPAgentId()) && !setMjDeviceStatusBySaasVo.getAgentId().equals(entityMjDeviceInfo.getPAgentId())) {
                        log.error("设备已指定其他代理商");
                        return ResultUtil.error(ResultEnum.Err_3020);
                    }
                }
                if (setMjDeviceStatusBySaasVo.getComId() != entityMjDeviceInfo.getPComId()) {
                    log.error("设备已指定其他单位");
                    return ResultUtil.error(ResultEnum.Err_3021);
                }

            }
        } catch (Exception exception) {
            log.error("SaaS平台获取设备信息失败", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "SaaS平台获取设备信息失败");
        }
        SetDeviceStatusVo setDeviceStatusVo = new SetDeviceStatusVo();
        setDeviceStatusVo.setDeviceNo(setMjDeviceStatusBySaasVo.getDeviceNo());
        setDeviceStatusVo.setComId(setMjDeviceStatusBySaasVo.getComId());
        if (setMjDeviceStatusBySaasVo.getAgentId()!=null){
            setDeviceStatusVo.setAgentId(Long.valueOf(setMjDeviceStatusBySaasVo.getAgentId()));
        }
        setDeviceStatusVo.setSaasNo(setMjDeviceStatusBySaasVo.getSaasNo());
//        setDeviceStatusVo.setSaasNo("2");
        setDeviceStatusVo.setStatus(setMjDeviceStatusBySaasVo.getStatus());
        this.AccessDeviceSetDeviceStatus(setDeviceStatusVo);
        return ResultUtil.success(entityMjDeviceInfo);
    }


    /**
     * 通过设备号获取单位id
     * */
    @PostMapping(AiotUrl.Url_Aiot_getCompanyIdByMachNo)
    public Result getCompanyIdByMachNo(String machNo){
        EntityMjDeviceInfo entityMjDeviceInfo=mjDeviceInfoService.selectDeviceInfo(machNo);
        if(entityMjDeviceInfo==null){
            return  ResultUtil.error(ResultEnum.Err_2023);
        }
        if(entityMjDeviceInfo.getComId()==0){
            return  ResultUtil.error(ResultEnum.Err_3010);
        }else{
            return  ResultUtil.success(entityMjDeviceInfo.getComId());
        }
    }




    private Date getCommTime(String machNo, Date commTime){
        Object obj = redisUtil.get("HttpAiotMJMachCommTime:"+machNo);
        if(obj!=null){
            return (Date) obj;
        }
        if(commTime==null){
            commTime = DateUtils.strToDate("2020-01-01 12:34:56");
        }
        redisUtil.set("HttpAiotMJMachCommTime:"+machNo,commTime);
        return commTime;
    }
}
